<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action=""
                            id="userSearchForm" lay-filter="userSearchFormFilter">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">姓名</label>
                            <div class="layui-input-inline">
                                <input type="text" id="searchName" name="searchName" 
                                       autocomplete="off" class="layui-input"
                                       placeholder="请输入姓名">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">院系</label>
                            <div class="layui-input-inline">
                                <select id="searchCollege" name="searchCollege" lay-filter="searchCollege">
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">专业</label>
                            <div class="layui-input-inline">
                                <select id="searchMajor" name="searchMajor" lay-filter="searchMajor">
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">班级</label>
                            <div class="layui-input-inline">
                                <input type="text" id="searchClazz" name="searchClazz" autocomplete="off" class="layui-input"
                                       placeholder="请输入班级">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">年级</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" id="searchGrade" name="searchGrade"
                                       placeholder="请选择入学年份"
                                       autocomplete="off">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" id="data-search-btn" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                            <button type="reset" id="data-reset-btn" class="layui-btn layui-btn-primary"
                                    lay-filter="data-reset-btn"><i class="layui-icon"></i> 重 置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加用户</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="removeBatch"> 批量删除
                </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="look">查看详情</a>
            <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit">修改</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="remove">删除</a>
        </script>

        <script type="text/html" id="checkStatusTable">
            <input type="checkbox" checked lay-skin="switch"
                   lay-text="启用|禁用" disabled>
        </script>

    </div>
</div>
<script>
    layui.use(['form', 'table','miniPage','element','laydate'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            laydate = layui.laydate,
            miniPage = layui.miniPage,
            initYear;

        form.render();

        function formInit() {
            //初始化加载院系
            let url = 'CollegeServlet';
            let params = {method: 'search'};
            let successFn = function (res) {
                res = JSON.parse(res);
                let colleges = res.data;
                for (let i = 0; i < colleges.length; i++) {
                    $('#searchCollege').append("<option value='"+colleges[i].id+"'>"+colleges[i].name+"</option>");
                }
                form.render('select');
            };
            $.get(url, params, successFn);
        }

        formInit();

        form.on('select(searchCollege)', function (data) {
            //清空目前专业下拉狂中的数据
            $('#searchMajor').empty();
            $('#searchMajor').append("<option value=''>请选择</option>");
            let college = data.value;
            let url = 'MajorServlet';
            let params = {method: 'search', collegeSearch: college};
            let successFn = function (res) {
                res = JSON.parse(res);
                let majors = res.data;
                for (let i = 0; i < majors.length; i++) {
                    $('#searchMajor').append("<option value='"+majors[i].id+"'>"+majors[i].name+"</option>");
                }
                form.render('select');
            }
            $.get(url, params, successFn);
        });

        let tableObj = table.render({
            elem: '#currentTableId',
            url: 'UserServlet?method=search',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                // {field: 'name', width: 80, title: '姓名',templet:'#nameTmp'},
                {field: 'name', width: 80, title: '姓名'},
                {field: 'college', width: 150, title: '院系', templet:'<div>{{d.college.name}}</div>'},
                {field: 'major', width: 150, title: '专业',templet:'<div>{{d.major.name}}</div>'},
                {field: 'clazz', title: '班级', width: 150},
                {field: 'grade', width: 80, title: '年级', sort: true},
                {field: 'phone', width: 180, title: '手机号码', sort: true},
                {title: '用户状态', minWidth: 160, toolbar: '#checkStatusTable', align: "center"},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [10, 20, 30, 40, 50],
            limit: 10,
            page: true,
            skin: 'line'
        });

        laydate.render({
            elem: '#searchGrade',
            type: 'year',
            trigger: 'click',
            ready: function (date) { // 控件在打开时触发，回调返回一个参数：初始的日期时间对象
                initYear = date.year;
            },
            change: function (value, date, endDate) { // 年月日时间被切换时都会触发。回调返回三个参数，分别代表：生成的值、日期时间对象、结束的日期时间对象
                var selectYear = date.year;
                var differ = selectYear - initYear;
                if (differ != 15 && differ != -15) {
                    if ($(".layui-laydate").length) {
                        $("#searchGrade").val(value);
                        $(".layui-laydate").remove();
                    }
                }
                initYear = selectYear;
            }
        })

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var content = miniPage.getHrefContent('page/user/userAdd.jsp');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加用户',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'removeBatch') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.confirm("确认删除这些信息吗？",function (index) {
                    $.ajaxSettings.async = false;
                    let successNumber = 0;
                    let failNumber = 0;

                    for(let i=0;i<data.length;i++){
                        let url = 'UserServlet';
                        let params = {method:'remove', id: data[i].id};
                        let successFn = function (res) {
                            if (res == 'true') {
                                successNumber++;
                            }else{
                                failNumber++;
                            }
                        };
                        $.post(url, params, successFn);
                    }
                    $.ajaxSettings.async = true;
                    table.reload('currentTableId');
                    layer.close(index);
                    layer.msg('[' + successNumber + "]条信息删除成功  /  [" + failNumber + "]条信息删除失败");
                })
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                let id = data.id;
                let url = "UserServlet?method=searchById&id=" + id;
                let successFn = function (res) {

                    if (res == 'null') {
                        layer.msg("记录不存在，请刷新",{icon: 1});
                        return false;
                    }

                    res = JSON.parse(res);
                    let params = "?username=" + res.username;
                    params += "&id=" + res.id;
                    params += "&password=" + res.password;
                    params += "&name=" + res.name;
                    params += "&college=" + res.college.id;
                    params += "&major=" + res.major.id;
                    params += "&clazz=" + res.clazz;
                    params += "&grade=" + res.grade;
                    params += "&schoolJob=" + res.schoolJob;
                    params += "&phone=" + res.phone;
                    params += "&QQ=" + res.qq;
                    params += "&role=" + res.role.id;
                    params += "&state=" + res.state;
                    params += "&remark=" + res.remark;
                    console.log(params);
                    var content = miniPage.getHrefContent('page/user/userModify.jsp'+params);
                    var openWH = miniPage.getOpenWidthHeight();

                    var index = layer.open({
                        title: '编辑用户',
                        type: 1,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: [openWH[0] + 'px', openWH[1] + 'px'],
                        offset: [openWH[2] + 'px', openWH[3] + 'px'],
                        content: content,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    return false;
                };
                $.get(url, successFn);


            } else if (obj.event === 'remove') {
                layer.confirm('真的删除行么', function (index) {
                    let url = 'UserServlet';
                    let params = {method:'remove',id:data.id};
                    let successFn = function(res){
                        if (res == 'true') {
                            obj.del();
                            layer.msg("删除成功",{icon:1});
                        }else{
                            layer.msg("删除失败",{icon:2});
                        }
                    }
                    $.post(url, params, successFn);

                    layer.close(index);
                });
            }else if(obj.event === 'look') {
                let id = data.id;
                let url = "UserServlet?method=searchById&id=" + id;
                let successFn = function (res) {

                    if (res == 'null') {
                        layer.msg("记录不存在，请刷新", {icon: 1});
                        return false;
                    }


                    res = JSON.parse(res);
                    console.log(res.grade);
                    let params = "?username=" + res.username;
                    params += "&name=" + res.name;
                    params += "&college=" + res.college.name;
                    params += "&major=" + res.major.name;
                    params += "&clazz=" + res.clazz;
                    params += "&grade=" + res.grade;
                    params += "&schoolJob=" + res.schoolJob;
                    params += "&phone=" + res.phone;
                    params += "&QQ=" + res.qq;
                    params += "&role=" + res.role.name;
                    params += "&state=" + res.state;
                    params += "&remark=" + res.remark;

                    var content = miniPage.getHrefContent('page/user/userDetail.jsp' + params);
                    var openWH = miniPage.getOpenWidthHeight();
                    var index = layer.open({
                        title: '查看详情',
                        type: 1,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: [openWH[0] + 'px', openWH[1] + 'px'],
                        offset: [openWH[2] + 'px', openWH[3] + 'px'],
                        content: content,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    return false;
                }

                $.get(url, successFn);
            }
        });


        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            let params = {
                page:{curr:1,limit:10},
                where:data.field
            }
            tableObj.reload(params);
            return false;
        });

        //当点击重置按钮时，重置搜索条件（按钮自带），也重置表格
        $('#data-reset-btn').click(function () {
            let params = {
                page:{curr:1,limit:10},
                where:null
            }
            tableObj.reload(params);
        })



    });
</script>